package facilius.controller.action;

import facilius.model.ServiceLocator;
import facilius.model.pojo.Aula;
import facilius.model.pojo.Material;
import java.io.File;
import java.io.FileInputStream;
import org.mentawai.core.BaseAction;
import org.mentawai.core.StreamConsequence;

/**
 *
 * @author Graciano
 */
public class LoadFileAction extends BaseAction {

    @Override
    public String execute() throws Exception {
        String consequence = ERROR;
        try {
            Long id = input.getLong("id");
            Material material = ServiceLocator.getMaterialService().readById(id);
            Long aulaId = material.getAula().getId();
            Aula aula = ServiceLocator.getAulaService().readById(aulaId);
            String path = org.mentawai.core.ApplicationManager.getRealPath() + "\\WEB-INF\\files\\" + aula.getId() + "\\" + material.getNome();

            File file = new File(path);

            if (file.exists()){
                FileInputStream fis = new FileInputStream(file);

                output.setValue(StreamConsequence.STREAM_KEY, fis);
                output.setValue(StreamConsequence.FILENAME_KEY, material.getNome().replace(" ", "_"));
                output.setValue(StreamConsequence.CONTENT_TYPE_KEY, material.getDescricao());
                consequence = SUCCESS;

            }else{
                ServiceLocator.getMaterialService().delete(material.getId());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return consequence;
    }
}
